package me.helllp.dake.generator.engine;

import freemarker.template.TemplateException;
import lombok.Getter;
import lombok.Setter;
import me.helllp.dake.generator.FreeMarkerUtil;
import me.helllp.dake.generator.config.GeneratorEngineConfiguration;
import me.helllp.dake.generator.meta.PomMetaData;
import me.helllp.dake.generator.meta.ProjectMetaData;
import me.helllp.dake.generator.utils.FileAndPathUtils;
import org.apache.commons.beanutils.BeanMap;
import org.apache.commons.lang3.ObjectUtils;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Getter
@Setter
public class PomGenerator extends AbstractGenerator {
    private PomMetaData pomMete;

    /**
     * 父亲依赖
     */
    private PomMetaData parent;

    /**
     * 依赖的信息列表
     */
    private List<PomMetaData> dependencyList;

    /**
     * plugIn信息列表
     */
    private List<PomMetaData> plugIns;

    /**
     * 项目元数据
     */
    private ProjectMetaData projectMetaData;

    public PomGenerator(ProjectMetaData projectMetaData) {
        this.projectMetaData = projectMetaData;
        pomMete = projectMetaData.getPom();
    }

    public PomGenerator() {
    }

    public void addDependency(List<PomMetaData> pomMetes) {
        dependencyList = ObjectUtils.isEmpty(dependencyList) ? new ArrayList<>() : dependencyList;
        dependencyList.addAll(pomMetes);
        // TODO 需要增加去重的逻辑
    }

    public void addDependency(PomMetaData pomMete) {
        dependencyList = ObjectUtils.isEmpty(dependencyList) ? new ArrayList<>() : dependencyList;
        dependencyList.add(pomMete);
        // TODO 需要增加去重的逻辑
    }

    public void addPlugin(List<PomMetaData> pomMetes) {
        plugIns = ObjectUtils.isEmpty(plugIns) ? new ArrayList<>() : plugIns;
        plugIns.addAll(pomMetes);
        // TODO 需要增加去重的逻辑
    }

    public void addPlugin(PomMetaData pomMete) {
        plugIns = ObjectUtils.isEmpty(plugIns) ? new ArrayList<>() : plugIns;
        plugIns.add(pomMete);
        // TODO 需要增加去重的逻辑
    }

    @Override
    public void initGenerator(GeneratorEngineConfiguration engineConfiguration) throws TemplateException, IOException, InvocationTargetException, IllegalAccessException {
        super.initGenerator(engineConfiguration);
        parent = new PomMetaData("me.helllp", "dake-parent", getEngineConfiguration().getDakeVersion());
    }

    @Override
    public void generator() throws TemplateException, IOException {
        BeanMap beanMap = new BeanMap(this);
        FreeMarkerUtil.genSrc(FileAndPathUtils.pathAppend(this.projectMetaData.getProjectPath(), "pom.xml") , "pom.ftl", (Map)beanMap);
    }
}
